import React, { useState, memo, useEffect, useRef } from 'react';
import { Row, Col, message, Button } from 'tdesign-react';
import { createFAQApi, getListApi, putFAQApi, getArtClassListApi, getTabsApi } from 'api/operation/faq';
import { uploadFileApi } from 'api/common';
import classnames from 'classnames';
import CommonStyle from 'styles/common.module.less';
import useLoading from 'hooks/useLoading';
import { createColumns } from 'utils/tableUtils';
import SakuraSearchForm from 'components/SakuraSearchForm';
import { handleUpdateStatus } from './consts';
import IppeakTable from 'components/IppeakTable';
import StatusSwitch from 'components/StatusSwitch';
import SakuraDrawer from 'components/SakuraDrawer';
import DetailDrawer from './detail';
import { filterEmptyValues } from 'utils';

export const SelectTable = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([0, 1]);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false);
  const [detailItem, setDetailItem] = useState<any>(null);
  const { loading, setLoading } = useLoading(false);
  const [opType, setOpType] = useState<'Add' | 'Edit'>('Add');
  const [editingItem, setEditingItem] = useState<any>(null);
  const [artClassList, setArtClassList] = useState<any[]>([]);
  const [ARTCLASSMAP, setARTCLASSMAP] = useState<any>([]);
  const [tabs, setTabs] = useState<any[]>([]);
  const columns = createColumns([
    {
      label: 'ID',
      key: 'id',
    },
    {
      label: '分类-中文',
      key: 'parent_id',
      width: '200',
      render: ({ row }: any) => {
        const categoryLabel = ARTCLASSMAP.find((item: any ) => item.value === row.parent_id)?.label || '-';
        return <span>{categoryLabel}</span>;
      },
    },
    {
      label: '标题-中文',
      key: 'title_zh',
      width: '250',
    },
    {
      label: '排序',
      key: 'sort',
    },
    {
      label: '状态',
      key: 'deleted',
      render: ({ row }: any) => (
        <StatusSwitch
          value={!row.deleted}
          loading={updatingRows.has(row.id)}
          onChange={(newValue) => handleUpdateStatus(newValue, row, setUpdatingRows, setTable)}
          row={row}
          activeText="启用"
          inactiveText="禁用"
        />
      ),
    },
    {
      label: '操作人',
      key: 'creator',
      width: '150',
    },
    {
      label: '操作时间',
      key:'created',
      width: '150',
      type:'date'
    },
    {
      label: '操作',
      key: 'op',
      width: '150',
              render: ({ row }: any) => (
         <>
         <Button  theme='primary' variant='text' onClick={() => handleDetailClick(row)}>
           详情
          </Button>
         <Button  theme='primary' variant='text' onClick={() => handleEditClick(row)}>
         编辑
       </Button></>
      ),
    },
  ]);
  const [table, setTable] = useState({
    list: [],
    total: 0,
    current: 1,
    pageSize: 10,
  });
  const [query, setQuery] = useState({
    page: 1,
    page_size: 10,
  });
  const [updatingRows, setUpdatingRows] = useState<Set<string | number>>(new Set());
  const drawerRef = useRef<any>(null);
  const formFields: any[] = [
    {
      label:'分类',
      name:'art_class',
      type:'select',
      options: ARTCLASSMAP,
      colWrap: {
        colSpan: 1.5,
        labelWidth: 60,
      },
    },
    {
      label: '状态',
      name: 'status',
      type: 'select',
      options: [{ label: '启用', value: 1 }, { label: '禁用', value: 2 }],
      colWrap: {
        colSpan: 1.5,
        labelWidth: 50,
      },
    },
  
  ];
  const { list, total, current, pageSize } = table;
  const fetchUserList = async (params?: any) => {
    setLoading(true);
    try {
      const res: any = await getListApi(({ ...params, ...query }));
      setLoading(false);
      setTable((pre: any) => ({
        ...pre,
        list: res.results.map((item: any)=>({
          ...item,
          title: item.title?.['zh-CN']?.title || '',
          en_title: item.title?.['en-US']?.title || '',
          content: item.content?.['zh-CN']?.content || '',
          en_content: item.content?.['en-US']?.content || '',
          art_class: item.parent_id,
          art_class_en: item.parent_id,
          title_zh: item.title?.['zh-CN']?.title || '',
          content_zh: item.content?.['zh-CN']?.content || '',
        })) || [],
        total: res.total || 0,
        pageSize: res.page_size || 10,
        current: res.page || 1,
      }));
    } catch (err) {
      console.log(err, 'err');
    }
  };
  function onSelectChange(value: (string | number)[]) {
    setSelectedRowKeys(value);
  }

  const handleAddClick = () => {
    setEditingItem(null);
    setOpType('Add');
    setDrawerVisible(true);
  };

  const handleEditClick = (row: any) => {
    const editData = { ...row, tag_id:row.tag&&Number(row.tag.replaceAll('*', '')) || '' };
    setEditingItem({...editData,status:Number(editData.deleted)>=1?1:0});
    setOpType('Edit');
    setDrawerVisible(true);
  };

  const handleDetailClick = (row: any) => {
    setDetailItem(row);
    setDetailVisible(true);
  };
  const handleDrawerSubmit = async (type: string, values: any, cb: () => void) => {
    try {
      const formData = filterEmptyValues({
        art_class: values.art_class || '', // 分类-中文
        art_class_en: values.art_class_en || '', // 分类-英文
        title: values.title || '', // 标题-中文
        en_title: values.en_title || '', // 标题-英文
        content: values.content || '', 
        en_content: values.en_content || '', 
        status: values.status !== undefined && values.status !== null ? Number(values.status) : undefined, 
        sort: values.sort || 0, 
        tag_id: values.tag_id || '',
      });
      let res;
      if (type === 'Add') {
        res = await createFAQApi(formData);
      } else if (type === 'Edit') {
        const editId = editingItem?.id;
        if (!editId) {
          throw new Error('编辑时缺少ID');
        }
        const editFormData = {
          ...formData,
          id: editId,
          tag_id: values.tag_id || 0,
        };
        res = await putFAQApi(editFormData);
      } else {
        throw new Error('未知的操作类型');
      }
      
      message.success(`${type === 'Add' ? '新增' : '编辑'}成功`);
      cb();
      setDrawerVisible(false);
      fetchUserList();
    } catch (err: any) {
      console.error('提交失败:', err);
      message.error('操作失败');
    }
  };

  const handleDrawerClose = () => {
    setDrawerVisible(false);
    setEditingItem(null);
  };
   // 统一的字段清除处理函数
   const handleFieldClear = (fieldName: string) => {
    setQuery((prev: any) => {
      const { [fieldName]: removed, ...rest } = prev || {};
      return { ...rest, };
    });
  };
  // SakuraDrawer表单字段配置 - 使用DrawerForm
  const drawerFormFields = [
    {
      name: 'art_class',
      label: '分类-中文',
      type: 'select' as const,
      options: ARTCLASSMAP.map((item: any) => ({
        label: item.label,
        value: item.value
      })),
      required: true,
      colSpan: 6,
      onChange: (value: any, form: any) => {
        if (!value) {
          form?.setFieldsValue({ art_class_en: undefined });
          return;
        }
        const selectedCategory = ARTCLASSMAP.find((item: any) => item.value === value);
        if (selectedCategory && form) {
          form.setFieldsValue({ art_class_en: value });
        }
      }
    },
    {
      name: 'art_class_en',
      label: '分类-英文',
      type: 'select' as const,
      options: ARTCLASSMAP.map((item: any) => ({
        label: item.labelEn,
        value: item.value
      })),
      disabled: true,
      required: true,
      colSpan: 6,
    },
    {
      name: 'title',
      label: '标题-中文',
      required: true,
      type: 'textarea' as const,
      colSpan: 12,
      maxLength: 60,
      textareaProps: {
        maxLength: 60,
        tips: '标题长度不能超过60个字符',
      },
      formItemStyle: {
        marginBottom:'5px'
      },
    },
    {
      name: 'en_title',
      label: '标题-英文',
      required: true,
      type: 'textarea' as const,
      colSpan: 12,
    },
    {
     name : 'content',
     label: '内容-中文',
     required: true,
     type: 'richEditor' as const,
     colSpan: 24,
    },
    {
     name : 'en_content',
     label: '内容-英文',
     required: true,
     type: 'richEditor' as const,
     colSpan: 24,
    },
    {
      name:'tag_id',
      label:'指定页面',
      options: tabs,
      type:'select' as const,
      colSpan:6,
    }, 
    {
      name:'sort',
      label:"排序",
      type:'inputNumber',
      colSpan:6,
      props: {
        theme:'column',
      },
      help: '排序越大，官网的显示越靠前',

    },
    {
      name:'status',
      label:"状态",
      type:'radio',
      options:[{label:'启用',value:0},{label:'禁用',value:1}],
      defaultValue:0,
      colSpan:12,
    },
   
  ];

  
  // 统一的 useEffect：组件挂载时和 query 变化时都会调用
  useEffect(() => {
    fetchUserList();
  }, [query]);

  useEffect(()=>{
    getArtClassListApi().then((res: any)=>{
      const artClassData = res.results.map((item: any)=>({
        ...item,
        i18n: JSON.parse(item.i18n),
      })).map((item: any)=>({
        label: item.i18n['zh-CN'].name,
        labelEn: item.i18n['en-US']?.name || item.i18n['zh-CN'].name, // 英文标签，如果没有则使用中文
        value: item.id
      })) || [];
      setARTCLASSMAP(artClassData);
    });
    getTabsApi().then((res: any)=>{
      setTabs(res.results.map((item: any)=>({
        label: item.name,
        value: item.id
      })));
    });
  },[])
  const handleSearch = (values: any) => {
    setQuery((pre) => ({
      ...pre,
      ...values,
      page: 1,
    }));
  };
  const handleReset = () => {
    setQuery((pre) => ({
      page: 1,
      page_size: 10,
    }));
  };

  return (
    <>
      <Row>
        <Col style={{width: '100%'}}>
          <SakuraSearchForm
            fields={formFields}
            onAddClick={handleAddClick}
            onFieldClear={handleFieldClear}
            onSearch={handleSearch}
            onReset={handleReset}
            createField={true}
          />
        </Col>
      </Row>
      <IppeakTable
        loading={loading}
        dataSource={list}
        columns={columns}
        rowKey='index'
        tableHeight={272}
        selectedRowKeys={selectedRowKeys}
        onSelectChange={onSelectChange}
        pagination={{
          pageSize,
          total,
          current,
          showJumper: true,
          onCurrentChange(current: number, pageInfo: any) {
            setQuery((pre) => ({
              ...pre,
              page: pageInfo.current,
            }));
          },
          onPageSizeChange(size: number) {
            setQuery((pre) => ({
              ...pre,
              page_size: size,
            }));
          },
        }}
      />
      <SakuraDrawer
        ref={drawerRef}
        visible={drawerVisible}
        onClose={handleDrawerClose}
        title="常见问题"
        type={opType}
        initialValues={editingItem}
        width="45%"
        size="large"
        placement="right"
        destroyOnClose={true}
        showCloseBtn={true}
        showConfirmBtn={true}
        confirmText="保存"
        cancelText="取消"
        onConfirm={handleDrawerSubmit}
        onCancel={handleDrawerClose}
        drawerFormFields={drawerFormFields}
        uploadApi={uploadFileApi}
      />
      <DetailDrawer visible={detailVisible} onClose={() => setDetailVisible(false)} data={detailItem} artClassMap={ARTCLASSMAP} tabs={tabs} />
      
      
    </>
  );
};

const selectPage: React.FC = () => (
  <div className={classnames(CommonStyle.pageWithPadding, CommonStyle.pageWithColor)}>
    <SelectTable />
  </div>
);

export default memo(selectPage);
